<template>
  <div class="app-container page-shop-info">
    <!-- 导航栏 -->
    <div class="nav-box">
      <div class="nav">
        <div
          :class="['nav-item', navStatus === 0 ? 'active' : '']"
          @click="onSwitchNav(0)"
        >
          {{ $t('shopProcess.basicInfo') }}
        </div>
        <div
          :class="['nav-item', navStatus === 1 ? 'active' : '']"
          @click="onSwitchNav(1)"
        >
          {{ $t('shopProcess.businessInfo') }}
        </div>
        <div
          :class="['nav-item', navStatus === 2 ? 'active' : '']"
          @click="onSwitchNav(2)"
        >
          {{ $t('shopProcess.signUpInfo') }}
        </div>
        <div
          :class="['nav-item', navStatus === 3 ? 'active' : '']"
          @click="onSwitchNav(3)"
        >
          {{ $t('shopProcess.financeInfo') }}
        </div>
      </div>
    </div>
    <!-- 模块 -->
    <div class="shop-info-box">
      <alertTips
        :audit-status="auditStatus"
        :company-info-process-status="companyInfoProcessStatus"
        :status-remark="statusRemark"
        :shop-status="shopStatus"
        :id-card-collect-process-status="idCardCollectProcessStatus"
      />
      <!-- 基本信息 -->
      <div
        v-if="navStatus === 0"
        class="basic-info-mod"
      >
        <!-- 店铺审核状态 -->
        <div class="audit-status">
          <!-- status 0 未审核 1已通过 -1未通过 2平台下线 3 平台下线待审核 -->
          <!-- shopStatus 店铺状态(-1:已删除 0: 停业中 1:营业中 2:平台下线 3:待审核 4:店铺申请中 5.审核失败) -->
          <div
            v-if="shopAuditStatus"
            class="audit-item"
          >
            <span>{{ $t('shopProcess.auditStatus') }}：</span>
            <span v-if="shopAuditStatus.status === -1">{{ $t('shop.failed') }}</span>
            <span v-if="shopAuditStatus.status === 0">{{ $t('shop.unreviewed') }}</span>
            <span v-if="shopAuditStatus.status === 1">{{ $t('shop.passed') }}</span>
            <span v-if="shopAuditStatus.status === 2">{{ $t('shop.platformOffline') }}</span>
          </div>
          <div
            v-if="shopBasicInfo"
            class="audit-item"
          >
            <span>{{ $t('shopProcess.accountStatus') }}：</span>
            <span v-if="shopBasicInfo.accountStatus === 0">{{ $t('shopProcess.disable') }}</span>
            <span v-if="shopBasicInfo.accountStatus === 1">{{ $t('shopProcess.enable') }}</span>
            <span v-if="shopBasicInfo.accountStatus === -1">{{ $t('shopProcess.delete') }}</span>
          </div>
          <div
            v-if="shopBasicInfo"
            class="audit-item"
          >
            <span>{{ $t('shopProcess.shopStatus') }}：</span>
            <span v-if="shopBasicInfo.shopStatus === -1">{{ $t('shopProcess.deleted') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 0">{{ $t('shopProcess.closed') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 1">{{ $t('shopProcess.inOperation') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 2">{{ $t('shop.platformOffline') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 3">{{ $t('shopProcess.onlinePendingReview') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 4">{{ $t('shopProcess.shopApplication') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 5">{{ $t('shopProcess.storeOpenPendingReview') }}</span>
            <span v-if="shopBasicInfo.shopStatus === 6">{{ $t('shopProcess.onlineAuditFailure') }}</span>
          </div>
          <div
            v-if="isAuth('shop:shopDetail:applyOnline') && shopBasicInfo.shopStatus === 2 && paySettlementType !== 1"
            class="default-btn primary-btn"
            @click="onOfflineManageHandle"
          >
            {{ $t('shopProcess.applyOnline') }}
          </div>
        </div>

        <!-- 基本信息浏览页面 -->
        <shop-info-browsing
          v-if="isShopInfoBrowsing"
          @close-browse="onBasicInforModify"
        />
        <!-- 基本信息 -->
        <div
          v-if="!isShopInfoBrowsing"
          class="business-info-mod-wrap"
        >
          <div class="business-info-mod">
            <el-form
              ref="shopBasicInfoRef"
              label-width="140px"
              :model="shopBasicInfo"
              :rules="shopBasicInfoRules"

              @submit.prevent
            >
              <div class="ci-wrapper">
                <div class="left-info">
                  <!-- 店铺logo -->
                  <el-form-item
                    :label="$t('shopProcess.logo')"
                    prop="shopLogo"
                  >
                    <div class="business-license-box">
                      <div class="license-content">
                        <img-upload v-model="shopBasicInfo.shopLogo" />
                      </div>
                      <div class="upload-tips">
                        {{ $t('shopProcess.logoTips') }}
                      </div>
                    </div>
                  </el-form-item>
                  <el-form-item
                    :label="$t('shopProcess.merchantName')"
                    prop="merchantName"
                  >
                    <p class="txt">
                      <el-input
                        v-model="shopBasicInfo.merchantName"
                        :placeholder="$t('shopProcess.merchantNameInputTips')"
                        maxlength="10"
                        @blur="
                          shopBasicInfo.merchantName =
                            shopBasicInfo.merchantName ?
                              removeHeadAndTailSpaces(shopBasicInfo.merchantName) :
                              shopBasicInfo.merchantName
                        "
                      />
                    </p>
                  </el-form-item>
                  <el-form-item
                    :label="$t('shopProcess.shopName')"
                    prop="shopName"
                  >
                    <p class="txt">
                      <el-input
                        v-model="shopBasicInfo.shopName"
                        :placeholder="$t('shopProcess.shopNameInputTips')"
                        maxlength="20"
                        @blur="
                          shopBasicInfo.shopName =
                            shopBasicInfo.shopName ?
                              removeHeadAndTailSpaces(shopBasicInfo.shopName) :
                              shopBasicInfo.shopName
                        "
                      />
                    </p>
                  </el-form-item>
                  <el-form-item
                    :label="$t('shopProcess.tel')"
                    prop="tel"
                  >
                    <p class="txt">
                      <el-input
                        v-model="shopBasicInfo.tel"
                        maxlength="11"
                        oninput="value=value.replace(/[^\d*]/g,'')"
                        :placeholder="$t('shopProcess.telInputTips')"
                      />
                    </p>
                  </el-form-item>

                  <el-form-item
                    :label="$t('shopProcess.intro')"
                    prop="intro"
                  >
                    <el-input
                      v-model="shopBasicInfo.intro"
                      type="textarea"
                      :rows="4"
                      class="store-intro"
                      maxlength="200"
                      :placeholder="$t('shopProcess.introInput')"
                      @blur="
                        shopBasicInfo.intro =
                          shopBasicInfo.intro ?
                            removeHeadAndTailSpaces(shopBasicInfo.intro) :
                            shopBasicInfo.intro
                      "
                    />
                  </el-form-item>
                </div>

                <div class="right-info" />
              </div>
            </el-form>
          </div>
          <div class="footer">
            <div class="foot-box">
              <div
                v-if="isAuth('shop:shopDetail:save')"
                class="btn default-btn primary-btn"
                @click="onValidationShopBasicInfo"
              >
                {{ $t('shopProcess.saveBasicInfo') }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- /基本信息 -->

      <!-- 工商信息 -->
      <business-information-browse
        v-if="navStatus === 1 && isbusinessInformationBrowse"
        :company-info-process-status="companyInfoProcessStatus"
        @close-business-browse="onCloseBusinessBrowse"
      />
      <!-- 编辑页 -->
      <div v-if="navStatus === 1 && !isbusinessInformationBrowse">
        <div class="business-info-mod">
          <el-form
            ref="companyInfoFormRef"
            :model="companyInfoForm"
            :rules="companyInfoRule"
            :disabled="shopAuditStatus.status===0&&paySettlementType===1&&companyInfoProcessStatus===3"
            label-width="140px"

            @submit.prevent
          >
            <div class="ci-wrapper">
              <div class="left-info">
                <el-form-item
                  :label="$t('shopProcess.creditCode')"
                  prop="creditCode"
                >
                  <el-input
                    v-model="companyInfoForm.creditCode"
                    maxlength="20"
                    :placeholder="$t('shopProcess.creditCodeInputTips')"
                  />
                </el-form-item>
                <el-form-item
                  :label="$t('shopProcess.firmName')"
                  prop="firmName"
                >
                  <el-input
                    v-model="companyInfoForm.firmName"
                    maxlength="50"
                    :placeholder="$t('shopProcess.firmNameInputTips')"
                    @blur="
                      companyInfoForm.firmName =
                        companyInfoForm.firmName ?
                          removeHeadAndTailSpaces(companyInfoForm.firmName) :
                          companyInfoForm.firmName
                    "
                  />
                </el-form-item>
                <el-form-item
                  :label="$t('shopProcess.residence')"
                  prop="residence"
                >
                  <el-input
                    v-model="companyInfoForm.residence"
                    maxlength="50"
                    :placeholder="$t('shopProcess.residenceInputTips')"
                    @blur="
                      companyInfoForm.residence =
                        companyInfoForm.residence ?
                          removeHeadAndTailSpaces(companyInfoForm.residence) :
                          companyInfoForm.residence
                    "
                  />
                </el-form-item>
                <el-form-item
                  :label="$t('shopProcess.representative')"
                  prop="representative"
                >
                  <el-input
                    v-model="companyInfoForm.representative"
                    maxlength="20"
                    :placeholder="$t('shopProcess.representativeInputTips')"
                    @blur="
                      companyInfoForm.representative =
                        companyInfoForm.representative ?
                          removeHeadAndTailSpaces(companyInfoForm.representative) :
                          companyInfoForm.representative
                    "
                  />
                </el-form-item>
                <el-form-item
                  v-if="paySettlementType"
                  :label="$t('allinpay.corporateIdentityCard')"
                  prop="legalIds"
                >
                  <el-input
                    v-model="companyInfoForm.legalIds"
                    maxlength="18"
                    :placeholder="$t('allinpay.pleaseEnterIDCard')"
                  />
                </el-form-item>
                <el-form-item
                  v-if="paySettlementType"
                  :label="$t('allinpay.legalPhone')"
                  prop="legalPhone"
                >
                  <el-input
                    v-model="companyInfoForm.legalPhone"
                    maxlength="11"
                    :placeholder="$t('allinpay.pleaseEnterLegalPhone')"
                    @input="(val)=>{companyInfoForm.legalPhone=val.replace(/[^\d]/g,'')}"
                  />
                </el-form-item>
                <el-form-item
                  :label="$t('shopProcess.capital')"
                  class="capital-int"
                >
                  <el-input
                    v-model="companyInfoForm.capital"
                    prop="capital"
                    type="number"
                    :min="0"
                    :max="99999999"
                    @blur="onChangeNum"
                    @keydown="onChannelInputLimit"
                  >
                    <template #append>
                      <el-button>
                        {{ $t("shopProcess.tenThousandYuan") }}
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item
                  :label="$t('shopProcess.fountTime')"
                  prop="foundTime"
                >
                  <el-date-picker
                    v-model="companyInfoForm.foundTime"
                    type="date"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :placeholder="$t('admin.seleData')"
                    :disabled-date="disabledDate"
                  />
                </el-form-item>
                <el-form-item
                  :label="$t('shopProcess.businessTime')"
                  prop="startTime"
                >
                  <div style="display: flex">
                    <el-date-picker
                      v-model="companyInfoForm.startTime"
                      style="width:150px;"
                      type="date"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :placeholder="$t('shopProcess.startTime')"
                      clearable
                      @change="onValidateTime('startTime')"
                    />
                    <span style="margin: 0 10px">-</span>
                    <span class="end-time">
                      <el-date-picker
                        ref="endTimeRef"
                        v-model="companyInfoForm.endTime"
                        style="width:150px;"
                        type="date"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        :placeholder="(endTimeFlag && !companyInfoForm.endTime && companyInfoForm.startTime) ? '' : $t('shopProcess.endTime')"
                        clearable
                        :disabled="!companyInfoForm.startTime"
                        @change="onValidateTime('endTime')"
                        @focus="endTimeFlag = false"
                      />
                      <span
                        v-if="endTimeFlag && !companyInfoForm.endTime && companyInfoForm.startTime"
                        class="text"
                        @click="onFocusEndTime"
                      >
                        {{ $t('shopProcess.noFixedTerm') }}
                      </span>
                    </span>
                  </div>
                </el-form-item>
                <el-form-item
                  :label="$t('shopProcess.businessScope')"
                  prop="businessScope"
                  style="margin-bottom:30px;"
                >
                  <el-input
                    v-model="companyInfoForm.businessScope"
                    type="textarea"
                    resize="none"
                    :rows="4"
                    :placeholder="$t('shopProcess.businessScopeInputTips')"
                    maxlength="500"
                    @blur="
                      companyInfoForm.businessScope =
                        companyInfoForm.businessScope ?
                          removeHeadAndTailSpaces(companyInfoForm.businessScope) :
                          companyInfoForm.businessScope
                    "
                  />
                </el-form-item>
              </div>
              <div class="right-info">
                <!-- 还没添加数据 -->
                <!-- 营业执照电子版 -->
                <el-form-item
                  :label="$t('shopProcess.businessLicense')"
                  prop="businessLicense"
                >
                  <div class="business-license-box">
                    <div class="license-content">
                      <img-upload v-model="companyInfoForm.businessLicense" />
                      <div class="example-box">
                        <img
                          src="~@/assets/img/example-img/Business-license.png"
                          alt=""
                        >
                        <div class="tips">
                          {{ $t('shopProcess.example') }}
                        </div>
                      </div>
                    </div>
                    <div class="upload-tips">
                      {{ $t('shopProcess.logoTips') }}
                    </div>
                  </div>
                </el-form-item>
                <!-- 法人身份证 -->
                <div class="id-box">
                  <div class="upload-content">
                    <div class="upload-img">
                      <el-form-item
                        class="idcard"
                        :label="$t('shopProcess.corporateIdentityCard')"
                        prop="identityCardFront"
                      >
                        <img-upload v-model="companyInfoForm.identityCardFront" />
                      </el-form-item>
                      <el-form-item
                        class="idcard"
                        label-width="0"
                        prop="identityCardLater"
                      >
                        <img-upload v-model="companyInfoForm.identityCardLater" />
                      </el-form-item>
                    </div>
                    <div :class="lang === 'en' ? 'en-left' : 'zh-left'">
                      <div class="upload-example">
                        <div class="example-box">
                          <img
                            src="~@/assets/img/example-img/idcard1.png"
                            alt=""
                          >
                          <div class="tips">
                            {{ $t('shopProcess.identityCardFront') }}
                          </div>
                        </div>
                        <div class="example-box">
                          <img
                            src="~@/assets/img/example-img/idcard2.png"
                            alt=""
                          >
                          <div class="tips">
                            {{ $t('shopProcess.identityCardLater') }}
                          </div>
                        </div>
                      </div>
                      <div class="upload-tips">
                        {{ $t('shopProcess.identityCardTips') }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-form>
        </div>
        <div
          v-if="navStatus === 1"
          class="footer"
        >
          <div class="foot-box">
            <div
              v-if="isAuth('shop:shopCompany:save') && !paySettlementType"
              class="btn default-btn primary-btn"
              @click="onSubmitBusinessReview"
            >
              {{ $t('shopProcess.saveSubmit') }}
            </div>

            <div
              v-if="isAuth('shop:shopCompany:save') && paySettlementType===1 && !(shopAuditStatus.status===0&&companyInfoProcessStatus===3)"
              class="btn default-btn primary-btn"
              @click="onSubmitBusinessReview"
            >
              确认提交
            </div>
          </div>
        </div>
      </div>
      <!-- /工商信息 -->

      <!-- 签约信息 -->
      <div
        v-if="navStatus === 2"
        class="contract-info table-box"
      >
        <!-- 签约类目 -->
        <div class="s-category-item s-item">
          <div class="apply-sign">
            <div class="table-data-title">
              <div class="text">
                <span class="stress">*</span>{{ $t('shopProcess.signingCategory') }}
              </div>
              <div class="tips">
                {{ $t('shopProcess.preSigned') }}
                <span class="txt-bold">{{ signCategoryList.length }}</span>
                {{ $t('shopProcess.piece') }}{{ $t('shopProcess.category') }}，
                {{ $t('shopProcess.mostAdd') }}
                <span class="txt-bold">200</span>
                {{ $t('shopProcess.piece') }}{{ $t('shopProcess.category') }}
              </div>
            </div>
            <div>
              <div
                v-if="showSignCategoriesBtn && isAuth('shop:shopCategory:apply')"
                class="default-btn primary-btn apply-btn"
                @click="onAddOrUpdate(1)"
              >
                {{ signCategoryAuditSwitch ? $t('shopProcess.applySigningCategory') : $t('shopProcess.addSigningCategory') }}
              </div>
              <div
                v-if="signCategoriesApplyInfo && (signCategoriesApplyInfo.status === 0 || signCategoriesApplyInfo.status === -1)"
                class="default-btn primary-btn apply-btn"
                @click="onViewSignApply"
              >
                {{ $t('shopProcess.seeApplySigningCategory') }}
              </div>
            </div>
          </div>
          <div class="si-content">
            <el-table
              :data="signCategoryList"
              header-cell-class-name="table-header"
              style="width: 100%"
            >
              <el-table-column
                prop="name"
                :label="$t('shopProcess.categoryName')"
              />
              <el-table-column
                prop="parentName"
                :label="$t('shopProcess.parentCategoryName')"
              />
              <el-table-column
                prop="platformRate"
                :label="$t('shopProcess.categoryRate')"
              >
                <template #default="{ row }">
                  <div v-if="row.customizeRate || row.customizeRate === 0 || row.platformRate || row.platformRate === 0">
                    <span v-if="row.customizeRate === null">{{ row.platformRate }} %</span>
                    <span v-else>{{ row.customizeRate }} %</span>
                  </div>
                  <div v-else>
                    --
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="qualifications"
                :label="$t('shopProcess.categoryQualifications')"
              >
                <template #default="{row}">
                  <div
                    v-if="row.imgs.length"
                    class="img-box"
                  >
                    <el-image
                      v-for="(img,index) in row.imgs"
                      :key="index"
                      class="rotating-img"
                      :src="checkFileUrl(img)"
                      preview-teleported
                      fit="cover"
                      :preview-src-list="checkFileUrl(row.imgs)"
                      :initial-index="initialIndex"
                      @click="initialIndex=index"
                    />
                  </div>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="categoryStatus"
                :label="$t('shopProcess.categoryStatus')"
              >
                <template #default="scope">
                  <div
                    v-if="scope.row.categoryStatus === 1"
                    class="tag-txt"
                  >
                    {{ $t('publics.normal') }}
                  </div>
                  <div
                    v-if="scope.row.categoryStatus === 0"
                    class="tag-txt red-tag-txt"
                  >
                    {{ $t('publics.LowerShelf') }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('crud.menu')"
                width="100"
                align="center"
              >
                <template #default="scope">
                  <div
                    class="default-btn text-btn"
                    @click="onCategoryDelete(scope.row)"
                  >
                    {{ $t('crud.delBtn') }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 签约品牌 -->
        <div class="s-brand-item s-item">
          <div class="apply-sign">
            <div class="table-data-title">
              <div class="text">
                {{ $t('shopProcess.signingBrand') }}
              </div>
              <div class="tips">
                {{ $t('shopProcess.preSigned') }}
                <span class="txt-bold">{{ signedBrands.length }}</span>
                {{ $t('shopProcess.piece') }}{{ $t('shopProcess.brand') }}，
                {{ $t('shopProcess.mostAdd') }}
                <span class="txt-bold">50</span>
                {{ $t('shopProcess.piece') }}{{ $t('shopProcess.brand') }}
              </div>
            </div>
            <div>
              <div
                v-if="isAuth('shop:shopBrand:apply')"
                class="default-btn primary-btn apply-btn"
                @click="onAddOrUpdate(2)"
              >
                {{ $t('shopProcess.applySigningBrand') }}
              </div>
            </div>
          </div>
          <div class="si-content main-container">
            <div class="table-con">
              <el-table
                :data="signedBrands"
                header-cell-class-name="table-header"
                style="width: 100%"
              >
                <el-table-column
                  prop="name"
                  :label="$t('shopProcess.brandName')"
                >
                  <template #default="scope">
                    <span class="table-cell-text">{{ scope.row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="firstLetter"
                  :label="$t('shopProcess.firstLetter')"
                />
                <el-table-column
                  prop="platformRate"
                  :label="$t('shopProcess.brandLogo')"
                >
                  <template #default="scope">
                    <div class="brand-logo">
                      <el-image
                        v-if="scope.row.imgUrl"
                        class="rotating-img"
                        preview-teleported
                        fit="cover"
                        :src="checkFileUrl(scope.row.imgUrl)"
                        :preview-src-list="[checkFileUrl(scope.row.imgUrl)]"
                      />
                      <span v-else>--</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="imgs"
                  :label="$t('shopProcess.brandQualifications')"
                >
                  <template #default="{row}">
                    <div
                      v-if="row.imgs.length"
                      class="brand-logo"
                    >
                      <el-image
                        v-for="(img,index) in row.imgs"
                        :key="index"
                        class="rotating-img"
                        :src="checkFileUrl(img)"
                        preview-teleported
                        fit="cover"
                        :preview-src-list="checkFileUrl(row.imgs)"
                        :initial-index="initialIndex"
                        @click="initialIndex=index"
                      />
                    </div>
                    <div v-if="!row.imgs.length">
                      --
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="brandStatus"
                  :label="$t('shopProcess.brandStatus')"
                >
                  <template #default="scope">
                    <div
                      v-if="scope.row.brandStatus === 1"
                      class="tag-txt"
                    >
                      {{ $t('publics.normal') }}
                    </div>
                    <div
                      v-if="scope.row.brandStatus === 0"
                      class="tag-txt red-tag-txt"
                    >
                      {{ $t('publics.LowerShelf') }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('crud.menu')"
                  width="100"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      type="primary"
                      link
                      @click="onBrandDelete(scope.row)"
                    >
                      {{ $t('crud.delBtn') }}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <!-- 签约有效期 -->
        <div
          v-if="paySettlementType!==1"
          class="s-sign-item s-item"
        >
          <div class="table-data-title">
            <div class="text">
              <span class="stress">*</span>{{ $t('shopProcess.validityPeriodOfContract') }}
            </div>
            <div class="tips">
              {{ $t('shopProcess.validPeriod') }}
            </div>
          </div>
          <div class="si-content">
            <div class="contract-time-box">
              <el-date-picker
                v-model="shopBasicInfo.contractStartTime"
                style="width:170px;"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('shopProcess.startTime')"
                disabled
              />
              <span style="margin: 0 10px">-</span>
              <div class="end-time">
                <el-date-picker
                  v-model="shopBasicInfo.contractEndTime"
                  style="width:170px;"
                  type="date"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="shopBasicInfo.contractStartTime&& !shopBasicInfo.contractEndTime ? '' : $t('shopProcess.endTime')"
                  disabled
                />
                <span
                  v-if="shopBasicInfo.contractStartTime&& !shopBasicInfo.contractEndTime"
                  class="text disable"
                >
                  {{ $t('shopProcess.noFixedTerm') }}
                </span>
              </div>
            </div>
          </div>
        </div>
        <!-- 商家类型 -->
        <div class="s-sign-item s-item">
          <div class="table-data-title">
            <div class="text">
              <span class="stress">*</span>{{ $t('shopProcess.shopType') }}
            </div>
          </div>
          <div class="si-content">
            <div>
              <el-radio
                v-model="shopBasicInfo.type"
                disabled
                :label="0"
              >
                {{ $t('shopProcess.ordinaryShop') }}
              </el-radio>
              <el-radio
                v-model="shopBasicInfo.type"
                disabled
                :label="1"
              >
                {{ $t('shopProcess.preferredGoodShop') }}
              </el-radio>
            </div>
          </div>
        </div>
      </div>
      <!-- /签约信息 -->

      <!-- 财务信息 -->
      <div
        v-if="navStatus === 3"
        class="financial-info"
      >
        <!-- 通联开启情况下，申请待审核和审核成功显示 -->
        <template v-if="(paySettlementType===1 && !(companyInfoProcessStatus===0 || companyInfoProcessStatus===3) || paySettlementType !== 1)">
          <div class="table-data-title">
            <div class="text">
              <span class="stress">*</span>{{ $t('shopProcess.settlementAccount') }}
            </div>
            <div
              v-if="paySettlementType!==1"
              class="tips"
            >
              {{ $t('shopProcess.added') }}
              <span class="txt-bold">{{ settlementAccounts.length }}</span>
              {{ $t('shopProcess.piece') }}&nbsp;{{ $t('shopProcess.settlementAccount') }}，{{ $t('shopProcess.mostAdd') }}
              <span class="txt-bold">5</span>
              {{ $t('shopProcess.piece') }}&nbsp;{{ $t('shopProcess.settlementAccount') }}
            </div>
            <div
              v-if="paySettlementType===1"
              class="tips"
            >
              {{ $t('allinpay.added') }}
              <span class="txt-bold">{{ cardNumber }}</span>
              {{ $t('allinpay.added2') }}
              <span class="txt-bold">10</span>
              {{ $t('allinpay.added3') }}
              <span>
                ，
                <span class="txt-bold">1</span>
                {{ $t('allinpay.added4') }}
              </span>
              <span v-if="mobile">
                {{ $t('allinpay.addedPhone') }}<span class="txt-bold">{{ mobile }}</span>
              </span>
            </div>
          </div>

          <div
            v-if="(settlementAccounts.length < 5 || (paySettlementType===1 && (legalCardNumber<1 || cardNumber<10))) && isAuth('shop:shopBankCard:save')"
            class="default-btn primary-btn create-btn"
            @click="onShowDialog(null)"
          >
            {{ $t('shopProcess.addSettlementAccount') }}
          </div>
          <div
            v-if="!mobile && paySettlementType===1"
            class="default-btn primary-btn create-btn"
            @click="onShowMobileDialog"
          >
            {{ $t('allinpay.beTiedPhone') }}
          </div>
          <div
            v-if="mobile && paySettlementType===1"
            class="default-btn primary-btn create-btn"
            @click="onShowMobileDialog"
          >
            {{ $t('allinpay.unbinding') }}
          </div>
          <div
            v-if="!(legalAcctProtocolNo&&acctProtocolNo) && paySettlementType===1"
            class="default-btn primary-btn create-btn"
            @click="onShowSignDialog"
          >
            {{ $t('allinpay.signAgreement') }}
          </div>
        </template>
        <template v-else>
          <div class="table-data-title">
            <div class="text">
              <span class="stress">*</span>{{ $t('allinpay.clearingBankAccount') }}
            </div>
            <div class="tips">
              {{ $t('allinpay.pleaseAddPublicAccount') }}
            </div>
          </div>
        </template>
        <div class="table-con">
          <el-table
            v-if="(paySettlementType===1 && !(companyInfoProcessStatus===0 || companyInfoProcessStatus===3) || paySettlementType !== 1)"
            :data="settlementAccounts"
            header-cell-class-name="table-header"
            row-class-name="table-row-low"
            style="width: 100%"
          >
            <el-table-column
              prop="bankName"
              :label="$t('shopProcess.bankName')"
            />
            <el-table-column
              prop="recipientName"
              :label="$t('shopProcess.recipientName')"
            >
              <template #default="scope">
                <div class="recipient-name">
                  <span>{{ scope.row.recipientName }}</span>
                  <div
                    v-if="paySettlementType===1&&scope.row.bankCardPro===0"
                    class="tip"
                  >
                    {{ $t('allinpay.corporateAccount') }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :prop="paySettlementType===1?'bankCardNo':'cardNo'"
              :label="$t('shopProcess.account')"
            />
            <el-table-column
              prop="openingBank"
              :label="$t('shopProcess.openingBank')"
            />
            <el-table-column
              prop="isDefault"
              :label="$t('shopProcess.masterAccount')"
            >
              <template #default="scope">
                {{ scope.row.isDefault ? $t('shopProcess.yes') : $t('shopProcess.no') }}
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              width="230"
              :label="$t('publics.operating')"
            >
              <template #default="scope">
                <div class="text-btn-con">
                  <div
                    v-if="paySettlementType!==1"
                    class="default-btn text-btn"
                    :class="{'m-disable':!isAuth('shop:shopBankCard:update')}"
                    @click="onShowDialog(scope.row.shopBankCardId)"
                  >
                    {{ $t("crud.filter.modify") }}
                  </div>
                  <div
                    v-if="paySettlementType!==1||(paySettlementType===1&&scope.row.bankCardPro===0)"
                    class="default-btn text-btn"
                    :class="{'m-disable':!isAuth('shop:shopBankCard:delete')}"
                    @click="onDeleteBankCartById(scope.row.cardNo, scope.row.shopBankCardId)"
                  >
                    {{ paySettlementType===1?$t('allinpay.unbinding'):$t("text.delBtn") }}
                  </div>
                  <div
                    v-if="!scope.row.isDefault"
                    class="default-btn text-btn"
                    :class="{'m-disable':!isAuth('shop:shopBankCard:default')}"
                    @click="onSetMainAccountById(scope.row.shopBankCardId)"
                  >
                    {{ $t("shopProcess.setMainAccount") }}
                  </div>
                  <div
                    v-if="scope.row.isDefault === 1"
                    class="default-btn text-btn"
                    :class="{'m-disable':!isAuth('shop:shopBankCard:noDefault')}"
                    @click="onSetNotMainAccountById(scope.row.shopBankCardId)"
                  >
                    {{ $t("shopProcess.setNotMainAccount") }}
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <template v-if="(companyInfoProcessStatus===0 || companyInfoProcessStatus===3) && paySettlementType===1">
            <el-form
              ref="bankCartInfoFormRef"
              :model="bankCartInfoForm"
              :rules="bankCartInfoForm.rule"

              @submit.prevent
            >
              <el-table
                ref="bankTableRef"
                class="add-bank-info-table"
                :data="bankCartInfoForm.data"
                :header-cell-style="{height:'50px',background:'#F5F5F5',color:'#000','font-weight': '400'}"
                style="width: 100%"
              >
                <el-table-column
                  type="index"
                  :label="$t('number')"
                  width="80"
                />
                <el-table-column
                  prop="parentBankName"
                  :label="$t('allinpay.bankName')"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'data.' + scope.$index + '.parentBankName'"
                      :rules="bankCartInfoForm.rule.parentBankName"
                    >
                      <el-select
                        v-model="selectBank"
                        filterable
                        :placeholder="$t('allinpay.pleaseSelect')"
                        style="width:200px"
                        @change="onChangeBank"
                      >
                        <el-option
                          v-for="item in bankList"
                          :key="item.bankId"
                          :label="item.bankName"
                          :value="item.bankName"
                        />
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="bankName"
                  :label="$t('allinpay.branchName')"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'data.' + scope.$index + '.bankName'"
                      :rules="bankCartInfoForm.rule.bankName"
                    >
                      <el-input
                        v-model="scope.row.bankName"
                        maxlength="20"
                        :placeholder="$t('allinpay.forExample') + '南京市雨花区雨花支行'"
                        style="width:200px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="accountNo"
                  :label="$t('allinpay.businessPublicAccounts')"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'data.' + scope.$index + '.accountNo'"
                      :rules="bankCartInfoForm.rule.accountNo"
                    >
                      <el-input
                        v-model.trim="scope.row.accountNo"
                        maxlength="19"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        :placeholder="$t('allinpay.pleaseEntePublicAccount')"
                        style="width:200px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="unionBank"
                  :label="$t('allinpay.paymentLineNumber')"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'data.' + scope.$index + '.unionBank'"
                      :rules="bankCartInfoForm.rule.unionBank"
                    >
                      <el-input
                        v-model="scope.row.unionBank"
                        :placeholder="$t('allinpay.enterLineNumber')"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        maxlength="12"
                        style="width:200px"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            <div class="footer">
              <div class="foot-box">
                <div
                  class="btn"
                  @click="toNextStep"
                >
                  {{ $t('allinpay.submit') }}
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
      <!-- /财务信息 -->
    </div>

    <account-manage
      v-if="dialogVisible"
      ref="accountManageRef"
      :card-number="cardNumber"
      :legal-card-number="legalCardNumber"
      @refresh-data-list="onQueryShopFinancialInfo"
    />
    <offline-manage
      v-if="offlineManageVisible"
      ref="offlineDataRef"
      @rereapply-data-submit="onReReapplyDataSubmit"
    />

    <!-- 类目签约弹窗 -->
    <category-add-or-update
      v-if="cateAddOrUpdateVisible"
      ref="cateAddOrUpdateRef"
      :apply-for-sign="true"
      :signing-count="signCategoryList.length"
      :sign-audit-switch="signCategoryAuditSwitch"
      @close-popup="onClosePopup"
    />
    <!-- 品牌签约弹窗 -->
    <brand-add-or-update
      v-if="brandAddOrUpdateVisible"
      ref="brandAddOrUpdateRef"
      :apply-for-sign="true"
      :signing-count="signedBrands.length"
      @close-popup="onClosePopup"
    />

    <!-- 绑定手机号 -->
    <mobile-add-or-update
      v-if="mobileDialogVisible"
      ref="mobileAddOrUpdateRef"
      :is-have-mobile="!!mobile"
      @refresh-data-form="onQueryCompany"
    />
    <!-- 签约协议 -->
    <sign-acct-protocol
      v-if="signDialogVisible"
      ref="signAcctProtocolRef"
      :acct-protocol-no="acctProtocolNo"
      :legal-acct-protocol-no="legalAcctProtocolNo"
      :mobile="mobile"
      :legal-card-number="legalCardNumber"
    />

    <!-- 类目签约申请信息 -->
    <sign-apply
      v-if="signApplyVisible"
      ref="signApplyRef"
      @refresh-change="refreshChange"
    />
  </div>
</template>

<script setup>
import moment from 'moment'
import { isAuth } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isCreditCode, validNoEmptySpace, removeHeadAndTailSpaces, checkIDCard } from '@/utils/validate'
import accountManage from './components/shop-info-account-manage/index.vue'
import offlineManage from './components/shop-info-offline-manage/index.vue'
import shopInfoBrowsing from './components/shop-info-browsing/index.vue'
import categoryAddOrUpdate from '../../shop-process/components/category-add-or-update/index.vue'
import brandAddOrUpdate from '../../shop-process/components/brand-add-or-update/index.vue'
import businessInformationBrowse from './components/business-information-browse/index.vue'
import alertTips from './components/alert-tips/index.vue'
import mobileAddOrUpdate from './components/mobile-add-or-update/index.vue'
import signAcctProtocol from './components/sign-acct-protocol/index.vue'
import signApply from './components/sign-apply/index.vue'

import { Debounce } from '@/utils/debounce'

// 语言
const lang = ref(localStorage.getItem('bbcLang'))
const initialIndex = ref(0) // 图片预览索引

const validateMobile = (rule, value, callback) => {
  const phoneReg = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/
  const mobile = /^(?:(?:\+|00)86)?1\d{2}([\d*]{4})\d{4}$/
  if (phoneReg.test(value) || mobile.test(value)) {
    callback()
  } else {
    callback(new Error($t('shopProcess.telErrorTips')))
  }
}
const validateMerchantName = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('shopProcess.merchantNameNotEmpty')))
  } else {
    callback()
  }
}
const validateShopName = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('shopProcess.shopNameNotEmpty')))
  } else {
    callback()
  }
}

const shopBasicInfoRules = reactive({
  merchantName: [
    { required: true, message: $t('shopProcess.merchantNameNotEmpty'), trigger: 'blur' },
    { validator: validateMerchantName, trigger: 'blur' },
    { min: 2, max: 10, message: $t('shopProcess.merchantNameErrorTips'), trigger: 'blur' }
  ],
  shopName: [
    { required: true, message: $t('shopProcess.shopNameNotEmpty'), trigger: 'blur' },
    { validator: validateShopName, trigger: 'blur' },
    { min: 2, max: 20, message: $t('shopProcess.shopNameInputTips'), trigger: 'blur' }
  ],
  tel: [
    { required: true, message: $t('shopProcess.telNotEmpty'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ],
  shopLogo: [
    { required: true, message: $t('shopProcess.logoNotEmpty'), trigger: 'change' }
  ]
})

// 成立日期：今日之前可选
const disabledDate = (time) => {
  const date = moment().add(1, 'days').startOf('days')
  return (
    time.getTime() >= date.valueOf()
  )
}

const validateBusinessScope = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('shopProcess.businessScopeNotEmpty')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validRepresentative = (rule, value, callback) => {
  companyInfoForm.value.representative = companyInfoForm.value.representative.trim()
  if (companyInfoForm.value.representative.indexOf(' ') !== -1) {
    callback(new Error($t('shopProcess.inputAllSpace')))
  } else {
    callback()
  }
}
const vaildCreditCode = (rule, value, callback) => {
  if (!isCreditCode(value)) {
    callback(new Error($t('shopProcess.creditCodeErrorTips')))
  } else {
    callback()
  }
}
const validEmptyTab = (rule, value, callback) => {
  if (validNoEmptySpace(value)) {
    callback(new Error($t('shopProcess.inputAllSpace')))
  } else {
    callback()
  }
}
const validIDCard = (rule, value, callback) => {
  if (!value || !checkIDCard(value)) {
    callback(new Error($t('allinpay.PleaseEnterCorporateIDCard')))
  } else {
    callback()
  }
}
const companyInfoRule = reactive({
  creditCode: [
    { required: true, message: $t('shopProcess.creditCodeInputTips'), trigger: 'blur' },
    { validator: vaildCreditCode, trigger: 'blur' }
  ],
  firmName: [
    { required: true, message: $t('shopProcess.firmNameNotEmpty'), trigger: 'blur' },
    { validator: validEmptyTab, trigger: 'blur' }
  ],
  businessScope: [
    { required: true, message: $t('shopProcess.businessScopeNotEmpty'), trigger: 'blur' },
    { validator: validateBusinessScope, trigger: 'blur' }
  ],
  representative: [
    { required: true, message: $t('shopProcess.representativeNotEmpty'), trigger: 'blur' },
    { validator: validRepresentative, trigger: 'blur' }
  ],
  legalIds: [
    { required: true, message: $t('allinpay.corporateIdentityCardNotEmpty'), trigger: 'blur' },
    { validator: validIDCard, trigger: 'blur' }
  ],
  legalPhone: [
    { required: true, message: $t('allinpay.legalPhoneNotEmpty'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: $t('shopProcess.businessLicenseNotEmpty'), trigger: 'change' }
  ],
  identityCardFront: [
    { required: true, message: '上传法人身份证人像面', trigger: 'change' }
  ],
  identityCardLater: [
    { required: true, message: '上传法人身份证国徽面', trigger: 'change' }
  ]
})

const allinpayStore = useAllinpayStore()
const paySettlementType = computed(() => {
  return allinpayStore.paySettlementType
})
const shopStatus = computed(() => {
  return allinpayStore.shopStatus // 店铺状态 -1:已删除 0: 停业中 1:营业中 2:平台下线 3:待审核 4:店铺申请中 5:申请失败 6:上线申请中
})
const idCardCollectProcessStatus = computed(() => {
  return allinpayStore.idCardCollectProcessStatus // 影印件采集审核状态 0.未上传 1.待审核 2.只有工商认证通过 3.只有法人信息通过 4.均审核通过
})

const companyInfoProcessStatus = ref(-1) // 企业信息审核状态 0.未提交 1.待审核 2.审核成功 3.审核失败
const isbusinessInformationBrowse = ref(true)
watch(() => companyInfoProcessStatus.value, (val) => {
  if ((val === 0 || val === 3) && paySettlementType.value === 1) {
    http({
      url: http.adornUrl('/shop/shopCompany'),
      method: 'get',
      params: http.adornParams()
    }).then(data => {
      // 通联支付且审核不通过，则获取工商信息审核情况
      if (val === 3) {
        onGetmodifyInformation().then((res) => {
          if (res === 0) {
            isbusinessInformationBrowse.value = true
          }
        })
        return
      }
      if (data.newStatus !== 0 && paySettlementType.value === 1) {
        // 未提交审核，则显示工商信息编辑页
        isbusinessInformationBrowse.value = false
      }
    })
  }
}, {
  immediate: true
})

// 步骤
const navStatus = ref(0)
onMounted(() => {
  navStatus.value = parseInt(useRoute().query.navStatus) || 0

  // 通联签约返回页面参数处理
  if (paySettlementType.value === 1 && useRoute().query.isSuccess === '1') {
    ElMessage.success($t('allinpay.signSuccess'))
    navStatus.value = 3
    useRouter().push({
      query: {}
    })
  } else if (useRoute().query.isSuccess === '0') {
    ElMessage.error($t('allinpay.signFail'))
    navStatus.value = 3
    useRouter().push({
      query: {}
    })
  }

  // 查询基本信息
  onSwitchNav(navStatus.value)
  // 店铺审核状态
  onQueryShopAuditStatus()
  // 签约类目审核开关
  onGetSignSwitch()
})

// 获取签约类目审核开关
const signCategoryAuditSwitch = ref(false) // 是否开启签约类目审核
const onGetSignSwitch = () => {
  // 签约类目
  http({
    url: http.adornUrl('/sys/config/signingConfig'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      signCategoryAuditSwitch.value = JSON.parse(data).signingAudit
    }
  })
}

const onSwitchNav = (value) => {
  navStatus.value = value
  if (value === 1) {
    // 查询工商信息
    onQueryShopBusinessInfo()
  } else if (value === 2) {
    // 查询分类签约信息
    onGetSignCategoryList()
    // 查询分类申请信息
    onGetSignCategoryList(0)

    // 查询品牌签约信息
    onGetSignBrandList()
    // 查询品牌申请信息
    onGetSignBrandList(0)
  } else if (value === 3) {
    // 查询财务信息
    onQueryShopFinancialInfo()
    if ((companyInfoProcessStatus.value === 0 || companyInfoProcessStatus.value === 3) && paySettlementType.value === 1) {
      // 获取银行卡列表
      onGetBankList()
    }
    if (paySettlementType.value === 1 && companyInfoProcessStatus.value !== 0 && companyInfoProcessStatus.value !== 3) {
      // 查询企业信息
      onQueryCompany()
    }
  } else {
    // 查询基本信息
    onQueryShopBasicInfo()
  }
}

/**
 * 店铺审核状态
 */
// 店铺审核状态
const shopAuditStatus = ref({})
const onQueryShopAuditStatus = () => {
  http({
    url: http.adornUrl('/shop/shopDetail/getAuditingInfo'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    shopAuditStatus.value = data
  })
  onQueryShopBasicInfo()
}

/**
 * 店铺违规下线操作
 */
const offlineDataRef = ref(null)
const offlineManageVisible = ref(false) // 下线对话框
const onOfflineManageHandle = () => {
  offlineManageVisible.value = true
  // 获取最新的店铺违规下线事件信息
  http({
    url: http.adornUrl('/shop/shopDetail/getOfflineHandleEvent'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    nextTick(() => {
      offlineDataRef.value?.init(data)
    })
  })
}

/**
 * 提交上线申请
 */
let isSubmit = false
const onReReapplyDataSubmit = (value) => {
  const param = {
    eventId: value.eventId,
    reapplyReason: value.reapplyReason // 申请理由
  }
  if (isSubmit) {
    return
  }
  isSubmit = true
  http({
    url: http.adornUrl('/shop/shopDetail/auditApply'),
    method: 'POST',
    data: param
  }).then(() => {
    offlineManageVisible.value = false
    ElMessage({
      message: $t('allinpay.submitSuccess'),
      type: 'success',
      duration: 1000,
      onClose: () => onQueryShopAuditStatus()
    })
    isSubmit = false
  }).catch(() => {
    isSubmit = false
  })
}

/**
 * 查询基本信息
 */
const shopBasicInfo = ref({}) // 店铺基本信息
const acctProtocolNo = ref('') // 签约提现协议号
const legalAcctProtocolNo = ref('') // 法人签约提现协议号
const onQueryShopBasicInfo = () => {
  http({
    url: http.adornUrl('/shop/shopDetail/info'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      shopBasicInfo.value = data
      if (paySettlementType.value === 1) {
        acctProtocolNo.value = data.companyAcctProtocolNo // 签约信息
        legalAcctProtocolNo.value = data.legalAcctProtocolNo // 签约信息
        companyInfoProcessStatus.value = data.companyInfoProcessStatus
        allinpayStore.updateIdCardCollectProcessStatus(data.idCardCollectProcessStatus)
        allinpayStore.updateShopStatus(data.shopStatus)
      }
    }
  })
}
/**
 * 关闭工商信息浏览页
 */
const onCloseBusinessBrowse = () => {
  isbusinessInformationBrowse.value = false
  nextTick(() => {
    onQueryShopBusinessInfo()
  })
}

/**
 * 查询工商信息
 */
const companyInfoForm = ref({ // 店铺工商信息
  creditCode: '',
  firmName: '',
  residence: '',
  representative: '',
  capital: '',
  foundTime: '',
  startTime: '',
  endTime: '',
  businessScope: '',
  businessLicense: '',
  identityCardFront: '',
  identityCardLater: '',
  legalPhone: '',
  legalIds: ''
})
let endTimeFlag = ref(true)
const onQueryShopBusinessInfo = () => {
  http({
    url: http.adornUrl('/shop/shopCompany'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      companyInfoForm.value = data
      endTimeFlag = true
    }
  })
}

const endTimeRef = ref(null)
const onFocusEndTime = () => {
  endTimeRef.value?.focus()
}

/**
 * 注册资本输入框校验
 */
const onChangeNum = () => {
  const capital = companyInfoForm.value.capital
  companyInfoForm.value.capital = onCheckInput(capital)
  if (Number.parseFloat(companyInfoForm.value.capital) === 0) {
    companyInfoForm.value.capital = 0
  }
  if (Number.parseFloat(companyInfoForm.value.capital) > 99999999) {
    companyInfoForm.value.capital = 99999999
  }
}
/**
 * input输入框只允许输入正数和小数(保留小数点后两位)
 */
const onCheckInput = (num) => {
  if (num) {
    let tmpVal = num.replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}
/**
 * 输入框不允许输入'-'或'+'
 */
const onChannelInputLimit = (e) => {
  const key = e.key
  if (key === '-' || key === '+') {
    e.returnValue = false
    return false
  }
  return true
}

/**
 * 签约类目列表
 */
const signCategoryList = ref([]) // 店铺分类签约信息
const onGetSignCategoryList = (status = 1) => {
  http({
    url: http.adornUrl('/prod/category/listSigningCategory'),
    method: 'get',
    params: http.adornParams({
      status // 签约审核 0 未审核 1已通过 -1未通过
    })
  }).then(({ data }) => {
    if (data) {
      if (status === 1) {
        signCategoryList.value = data
        signCategoryList.value.forEach(item => {
          item.imgs = item.qualifications ? item.qualifications.split(',') : []
        })
      }
    }
    if (status === 1) {
      getAuditInfo(1)
    }
  })
}

/**
 * 获取签约品牌列表
 */
// 平台品牌签约信息
const signedBrands = ref([]) // 平台品牌+自定义品牌
const onGetSignBrandList = (status = 1) => {
  http({
    url: http.adornUrl('/admin/brand/listSigningBrand'),
    method: 'get',
    params: http.adornParams({
      status // 签约审核 0 未审核 1已通过 -1未通过
    })
  }).then(({ data }) => {
    if (status === 1) {
      signedBrands.value = data.platformBrandList
      signedBrands.value.forEach(el => {
        el.imgs = el.qualifications ? el.qualifications.split(',') : []
      })
    }
  })
}

/**
 * 编辑签约信息弹窗
 */
const cateAddOrUpdateRef = ref(null)
const brandAddOrUpdateRef = ref(null)
const cateAddOrUpdateVisible = ref(false) // 类目签约弹窗显隐
const brandAddOrUpdateVisible = ref(false) // 品牌签约弹窗显隐
const onAddOrUpdate = (type) => {
  if (type === 1) {
    cateAddOrUpdateVisible.value = true
    nextTick(() => {
      cateAddOrUpdateRef.value?.init()
    })
    return
  }
  if (type === 2) {
    brandAddOrUpdateVisible.value = true
    nextTick(() => {
      brandAddOrUpdateRef.value?.init('editor')
    })
  }
}

// 查看类目申请信息
const signApplyVisible = ref(false)
const signApplyRef = ref(null)
const onViewSignApply = () => {
  signApplyVisible.value = true
  nextTick(() => {
    signApplyRef.value?.init(1, signCategoriesApplyInfo.value)
  })
}
/**
 * 获取签约审核信息
 * @param type 类型：1：分类 2：品牌
 */
const showSignCategoriesBtn = ref(false)
const signCategoriesApplyInfo = ref(null)
const getAuditInfo = (type) => {
  if (!isAuth('shop:signCategory:view')) return
  http({
    url: http.adornUrl('/shop/signingAuditing/auditInfo'),
    method: 'get',
    params: http.adornParams({
      type
    })
  }).then(({ data }) => {
    // data.status 0 未审核 1已通过 -1未通过
    if (type === 1) {
      showSignCategoriesBtn.value = !data || (data && data.status !== 0)
      signCategoriesApplyInfo.value = data || null
    }
  })
}
const refreshChange = () => {
  // 查询分类申请信息
  onGetSignCategoryList(0)
  getAuditInfo(1)
  onGetSignCategoryList()
}
/**
 * 关闭弹窗
 */
const onClosePopup = (val) => {
  if (val === 'category') {
    cateAddOrUpdateVisible.value = false
    onGetSignCategoryList()
    // 查询分类申请信息
    onGetSignCategoryList(0)
  } else if (val === 'brand') {
    brandAddOrUpdateVisible.value = false
    onGetSignBrandList()
    // 查询品牌申请信息
    onGetSignBrandList(0)
  }
}

/**
 * 查询财务信息
 */
// 店铺财务信息
const settlementAccounts = ref([])
const legalCardNumber = ref(0) // 法人账户数量
const cardNumber = ref(0) // 非法人账户数量
const bankCartInfoForm = reactive({
  data: [
    {
      bankName: '',
      recipientName: '',
      cardNo: '',
      accountNo: '', // 企业对公账户
      parentBankName: '', // 开户银行名称
      unionBank: '', // 支付行号 12位数字
      bankCardPro: 1 // 银行卡属性 0法人 1企业对公
    }
  ],
  rule: {
    bankName: [
      { required: true, message: $t('allinpay.branchTip'), trigger: 'blur' },
      { min: 2, max: 20, message: $t('allinpay.branchTip2'), trigger: 'blur' },
      { validator: validEmptyTab, trigger: 'blur' }
    ],
    cardNo: [
      { required: true, message: $t('allinpay.accNoNull'), trigger: 'blur' },
      { validator: validEmptyTab, trigger: 'blur' }
    ],
    accountNo: [
      { required: true, message: $t('allinpay.pleaseEntePublicAccount'), trigger: 'blur' }
    ],
    parentBankName: [
      { required: true, message: $t('allinpay.pleaseEnterBankName'), trigger: 'change' }
    ],
    unionBank: [
      { required: true, message: $t('allinpay.enterLineNumber'), trigger: 'blur' },
      { min: 12, max: 12, message: $t('allinpay.enterLineNumber2'), trigger: 'blur' }
    ]
  }
})
const selectBank = ref('') // 选择的银行，通联
const onQueryShopFinancialInfo = () => {
  http({
    url: http.adornUrl('/shop/shopBankCard/getShopBankCardList'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (paySettlementType.value === 1 && data && data.length > 0) {
      legalCardNumber.value = data.filter(item => item.bankCardPro === 0).length
      cardNumber.value = data.length - legalCardNumber.value
      bankCartInfoForm.data = [{
        ...data[0],
        parentBankName: data[0].bankName,
        bankName: data[0].openingBank,
        accountNo: data[0].bankCardNo
      }]
      selectBank.value = data[0].bankName
    }
    settlementAccounts.value = data
  })
}

/**
 * 更新基本信息
 */
const shopBasicInfoRef = ref(null)
const userStore = useUserStore()
const isShopInfoBrowsing = ref(true)
const onValidationShopBasicInfo = () => {
  shopBasicInfoRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    http({
      url: http.adornUrl('/shop/shopDetail'),
      method: 'PUT',
      data: http.adornData(shopBasicInfo.value)
    })
      .then(() => {
        ElMessage({
          message: $t('shopProcess.baseSaveSuccess'),
          type: 'success',
          duration: 1000,
          onClose: () => {
            isShopInfoBrowsing.value = true
          }
        })
        userStore.login()
      }).catch(() => {
        isShopInfoBrowsing.value = true
      })
  })
}

/**
 * 提交工商信息审核
 */
const companyInfoFormRef = ref(null)
let isSubmitBusinessReview = false
const onSubmitBusinessReview = () => {
  if (isSubmitBusinessReview) {
    return
  }
  companyInfoFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    isSubmitBusinessReview = true
    http({
      url: http.adornUrl('/shop/companyAuditing/applyChangeCompanyInfo'),
      method: 'post',
      data: http.adornData(companyInfoForm.value)
    }).then(() => {
      ElMessage({
        message: $t('shopProcess.auditTip1'),
        type: 'success',
        duration: 1000,
        onClose: () => {
          isSubmitBusinessReview = false
          isbusinessInformationBrowse.value = true
          if (paySettlementType.value === 1) {
            onGetmodifyInformation()
            if ((companyInfoProcessStatus.value === 0 || companyInfoProcessStatus.value === 3)) {
              onSwitchNav(3)
            }
          }
        }
      })
    }).catch(() => {
      isSubmitBusinessReview = false
      // isbusinessInformationBrowse.value = true
    })
  })
}

/**
 * 新增/修改账号
 */
const accountManageRef = ref(null)
const dialogVisible = ref(false)
const onShowDialog = (shopBankCardId) => {
  dialogVisible.value = true
  nextTick(() => {
    accountManageRef.value?.init(shopBankCardId)
  })
}

/**
 * 删除银行卡
 */
const onDeleteBankCartById = (cardNo, shopBankCardId) => {
  if (paySettlementType.value === 1) {
    ElMessageBox.confirm('是否解绑法人账号?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      http({
        url: http.adornUrl('/shop/allinpay/company/unbindBankCard'),
        method: 'put',
        data: http.adornData({ shopBankCardId, cardNo })
      }).then(() => {
        ElMessage({
          message: '解绑成功',
          type: 'success',
          duration: 1000
        })
        onQueryShopFinancialInfo()
      })
    }).catch(() => {})
    return
  }
  const tailNumber = cardNo.substring(cardNo.length - 4)
  ElMessageBox.confirm($t('shopProcess.shopBankCardDeletePre') + ' ' + `${tailNumber}` + ' ' + $t('shopProcess.shopBankCardDeleteAfter'), $t('text.tips'), {
    confirmButtonText: $t('order.confirm'),
    cancelButtonText: $t('order.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl(`/shop/shopBankCard/${shopBankCardId}`),
      method: 'DELETE',
      params: http.adornParams()
    }).then(() => {
      ElMessage({
        message: $t('shopProcess.deleteSuccessfully'),
        type: 'success',
        duration: 1000
      })
      onQueryShopFinancialInfo()
    })
  }).catch(() => {})
}

// 设置主账号
const onSetMainAccountById = (shopBankCardId) => {
  http({
    url: http.adornUrl('/shop/shopBankCard/setDefault'),
    method: 'PUT',
    data: http.adornData({
      shopBankCardId
    })
  }).then(() => {
    ElMessage({
      message: $t('shopProcess.setSuccess'),
      type: 'success',
      duration: 1000
    })
    onQueryShopFinancialInfo()
  })
}

// 取消主账号
const onSetNotMainAccountById = (shopBankCardId) => {
  http({
    url: http.adornUrl('/shop/shopBankCard/setNotDefault'),
    method: 'PUT',
    params: http.adornParams({
      shopBankCardId
    })
  }).then(() => {
    ElMessage({
      message: $t('shopProcess.cancelMainAccountSuccess'),
      type: 'success',
      duration: 1000
    })
    onQueryShopFinancialInfo()
  })
}

const onCategoryDelete = (row) => {
  const obj = {
    categoryId: row.categoryId
  }
  ElMessageBox.confirm($t('publics.deletes'), $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/shop/signingAuditing/deleteSigningCategory'),
      method: 'delete',
      params: http.adornParams(obj)
    }).then(() => {
      ElMessage({
        message: $t('shopProcess.deleteSuccessfully'),
        type: 'success',
        duration: 1500,
        onClose: () => onGetSignCategoryList()
      })
    })
  }).catch(() => { })
}
const onBrandDelete = (row) => {
  const obj = {
    brandShopId: row.brandShopId
  }
  ElMessageBox.confirm($t('publics.deletes'), $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/shop/signingAuditing/deleteSigningBrand'),
      method: 'delete',
      params: http.adornParams(obj)
    }).then(() => {
      ElMessage({
        message: $t('shopProcess.deleteSuccessfully'),
        type: 'success',
        duration: 1500,
        onClose: () => onGetSignBrandList()
      })
    })
  }).catch(() => { })
}
const onValidateTime = (value) => {
  if (value === 'endTime') {
    endTimeFlag = true
    if (!companyInfoForm.value.endTime) companyInfoForm.value.endTime = undefined
  } else {
    endTimeFlag = false
    if (!companyInfoForm.value.startTime) companyInfoForm.value.endTime = undefined
  }
  if (companyInfoForm.value.endTime && Date.parse(companyInfoForm.value.startTime) >= Date.parse(companyInfoForm.value.endTime)) {
    ElMessage({
      message: $t('shopProcess.businessStartEndTime'),
      type: 'error',
      duration: 1500
    })
    endTimeFlag = true
    companyInfoForm.value.endTime = undefined
  }
}
/**
 * 基本信息切换成编辑状态
 */
const onBasicInforModify = () => {
  isShopInfoBrowsing.value = false
  nextTick(() => {
    onQueryShopBasicInfo()
  })
}

// 获取并更新申请审核情况
const statusRemark = ref('')
const auditStatus = ref(null)
const onGetmodifyInformation = () => {
  return new Promise((resolve) => {
    // 走接口拿数据
    nextTick(() => {
      http({
        url: http.adornUrl('/shop/companyAuditing/auditInfo'),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        statusRemark.value = data.remarks
        auditStatus.value = data.status
        resolve(data.status)
      })
    })
  })
}

// 获取可选银行名称列表（通联）
const bankList = ref([]) // 银行列表，通联
const onGetBankList = () => {
  http({
    url: http.adornUrl('/publicBank/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    bankList.value = data
  })
}
// 查询企业信息（通联）
const mobile = ref('')
const onQueryCompany = () => {
  http({
    url: http.adornUrl('/shop/allinpay/company/getCompanyInfo'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    mobile.value = data.phone
  })
}

// 绑定/解绑手机号
const mobileAddOrUpdateRef = ref(null)
const mobileDialogVisible = ref(false)
const onShowMobileDialog = () => {
  mobileDialogVisible.value = true
  nextTick(() => {
    mobileAddOrUpdateRef.init(mobile.value)
  })
}

// 签约协议
const signAcctProtocolRef = ref(null)
const signDialogVisible = ref(false)
const onShowSignDialog = () => {
  signDialogVisible.value = true
  onQueryCompany()
  nextTick(() => {
    signAcctProtocolRef.value?.init()
  })
}
const onChangeBank = (value) => {
  bankCartInfoForm.data[0].parentBankName = value
}
const bankCartInfoFormRef = ref(null)
let submit = false
const toNextStep = Debounce(() => {
  bankCartInfoFormRef.value?.validate((valid) => {
    if (valid) {
      if (submit) {
        return
      }
      submit = true
      http({
        url: http.adornUrl('/shop/shopBankCard/allinpaySaveAndApplyShop'),
        method: 'post',
        data: http.adornData(bankCartInfoForm.data[0])
      }).then(() => {
        ElMessage({
          message: $t('allinpay.applicationSuccess'),
          type: 'success',
          duration: 1500
        })
        if (paySettlementType.value === 1) {
          location.reload()
        }
      }).finally(() => {
        submit = false
      })
    }
  })
}, 1500)

</script>

<style lang="scss" scoped>
  @use './index.scss';
</style>
